/*
 *
 * System2 Simulation Framework
 * Copyright (C) 2011 - 2012 Jacob Dawid
 * jacob.dawid@googlemail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "blockgraphicsitem.h"
#include <QStyleOptionGraphicsItem>
#include <QVariant>

namespace System2 {
    BlockGraphicsItem::BlockGraphicsItem(Block *block)
        : QGraphicsItem() {
        setFlags(QGraphicsItem::ItemIsMovable
               | QGraphicsItem::ItemIsSelectable
               | QGraphicsItem::ItemSendsGeometryChanges);
        m_block = block;

        m_dropShadowEffect = new QGraphicsDropShadowEffect();
        m_dropShadowEffect->setOffset(0);
        m_dropShadowEffect->setBlurRadius(30);
        setGraphicsEffect(m_dropShadowEffect);
    }

    BlockGraphicsItem::~BlockGraphicsItem() {
        delete m_dropShadowEffect;
    }

    QRectF BlockGraphicsItem::boundingRect() const {
        return QRectF(0, 0, 100, 62);
    }

    void BlockGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
        (void)event;
        update();
    }

    void BlockGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
        (void)event;
        update();
    }

    void BlockGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
        (void)widget;
        painter->setClipRect(option->exposedRect);
        painter->drawPixmap(0, 0, m_block->component()->symbol());
        if(isSelected()) {
            m_dropShadowEffect->setColor(QColor(0, 130, 200, 150));
        } else {
            m_dropShadowEffect->setColor(QColor(0, 20, 30, 150));
        }
    }

    Block *BlockGraphicsItem::block() {
        return m_block;
    }

    QVariant BlockGraphicsItem::itemChange(GraphicsItemChange change, const QVariant &value) {
        if(change == ItemPositionChange) {
            QPointF suggestedPosition = value.toPointF();
            return QPointF((int)suggestedPosition.x() - (int)suggestedPosition.x() % 120 - 50,
                           (int)suggestedPosition.y() - (int)suggestedPosition.y() % 82 - 31);
        }
        return QGraphicsItem::itemChange(change, value);
    }
}
